package com.sxwl.web.service.impl;

import com.sxwl.utils.PageUtils;
import com.sxwl.utils.Query;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxwl.web.dao.MenuDao;
import com.sxwl.web.entity.MenuEntity;
import com.sxwl.web.service.MenuService;


@Service("menuService")
public class MenuServiceImpl extends ServiceImpl<MenuDao, MenuEntity> implements MenuService {
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MenuEntity> page = this.page(
                new Query<MenuEntity>().getPage(params),
                new QueryWrapper<MenuEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public List<MenuEntity> getTree() {
        //查询所有分类
        List<MenuEntity> allList = this.baseMapper.selectList(null);
        //组装成父子树形结构
        List<MenuEntity> menuEntityList= allList.stream().filter(item ->
                //找到一级菜单
                item.getParentId().equals("0")
        ).map(item->{
            //查到所有子菜单
            item.setChildren(getChildrens(item,allList));
            return item;
        }).sorted((item1,item2)->{
            //排序
            return (item1.getOrderNum()==null?0:item1.getOrderNum())-(item2.getOrderNum()==null?0:item2.getOrderNum());
        }).collect(Collectors.toList());
        return  menuEntityList;
    }

    /**
     * 递归遍历所有菜单的子菜单
     * @param root
     * @param all
     * @return
     */
    private List<MenuEntity> getChildrens(MenuEntity root,List<MenuEntity> all){
        List<MenuEntity> entityList = all.stream().filter(item -> {
            //找到一级菜单
            return item.getParentId().equals(root.getId());
        }).map(menuEntity -> {
            //查到所有子菜单
            menuEntity.setChildren(getChildrens(menuEntity, all));
            return menuEntity;
        }).sorted((item1,item2)->{
            //排序
            return (item1.getOrderNum()==null?0:item1.getOrderNum())-(item2.getOrderNum()==null?0:item2.getOrderNum());
        }).collect(Collectors.toList());
        return entityList;
    }
}